import { Space, Table, Cascader, Modal, Image } from 'antd';
import { userinfoList, userinfotype, buildingList, userinfoDel, userinfoDelall, useAsk } from '../../apis/userInfo/index';
import { useNavigate } from 'react-router-dom';
import '../../assets/scss/userinfo.scss'
import { ExclamationCircleFilled } from '@ant-design/icons';
import {
  Button,
  Form,
  Input,
  message,
  Select,
  Pagination,

} from 'antd';
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom';

const UserInfo = (_props: any): JSX.Element => {
  const navigate = useNavigate()
  let url = process.env.REACT_APP_IMG_URL
  const [user, setUser] = useState({
    id: 32459,
    page: 1,
    psize: 5,
    key: '',
    name: '',
    mobile: '',
    houseno: '',
    state: '',
    usertype: '',
    buildingid: 0
  })
  const [list, setList] = useState()
  const [counts, setTotal]: any = useState([]);
  const [options, setOptions]: any = useState([])
  let fiel = {
    label: 'name',
    value: 'id',
    children: 'children'
  }
  const onChange: any = (value: number[]) => {
    console.log(value);
    let id = value.pop()
    console.log(id);
    setUser({ ...user, buildingid: value.slice(-2)[0] })
  };
  const getBuilding = async () => {
    let res = await buildingList()
    console.log(res, 'res');
    setOptions(res.data.list)
  }
  const getUserInfoList = async () => {
    let res = await userinfoList(user)
    console.log('res', res);
    setList(res.data.list)
    setTotal(res.data.counts)
  }
  const [typeList, setTypeList]: any = useState([])
  const getTypeList = async () => {
    let res = await userinfotype()
    console.log('typename', res);
    setTypeList(res.data.list)
  }
  useEffect(() => {
    getUserInfoList()
    getTypeList()
    getBuilding()
  }, [user])
  const del = (record: any) => {
    return async () => {
      let res: any = await userinfoDel({
        id: record
      })
      console.log('del', res);
      if (res && res.errCode == 10000) {
        getUserInfoList()
      }
    }
  }
  const selectDel = async () => {
    if (!delId) {
      message.open({
        type: 'error',
        content: '请选择要删除的数据',
      });
      return;
    }
    let res: any = await userinfoDelall({ ids: delId })
    console.log('delAll', res);
    if (res.errCode == 10000) {
      message.open({
        type: 'success',
        content: '批量删除成功',
      });
      getUserInfoList()
    }
  }
  const { confirm } = Modal;

  const updateState = async () => {
    confirm({
      title: '提示',
      icon: <ExclamationCircleFilled />,
      content: '确定审核吗',
      async onOk() {
        let res = await useAsk({ ids: delId })
        console.log('审核', res);
        getUserInfoList()
      },
      onCancel() {
        message.success('已取消')
      },
    });

  }
  const columns: any = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      align: 'center'
    },
    {
      title: '头像',
      align: 'center',
      size: '200px',
      key: 'photo',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Image src={url + record.photo} style={{ width: '50px', height: '50px' }} alt='' />
          {/* alt='暂无图片' */}
        </Space>
      ),
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      align: 'center'
    },
    {
      title: '业主类型',
      dataIndex: 'usertypeName',
      key: 'usertypeName',
      align: 'center'
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      align: 'center',
      render: (_: any, record: any) => (
        <Space size="middle">
          {record.sex == 1 ? '男' : '女'}
        </Space>
      ),
    },
    {
      title: '身份证号',
      dataIndex: 'cardid',
      key: 'cardid',
      align: 'center'
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
      align: 'center'
    },
    {
      title: '籍贯',
      dataIndex: 'usernative',
      key: 'usernative',
      align: 'center',
    },
    {
      title: '民族',
      dataIndex: 'nation',
      key: 'nation',
      align: 'center'
    },
    {
      title: '小区',
      dataIndex: 'building',
      key: 'building',
      align: 'center'
    },
    {
      title: '房间号',
      dataIndex: 'houseno',
      key: 'houseno',
      align: 'center'
    },
    {
      title: '审核状态',
      dataIndex: 'state',
      align: 'center',
      key: 'state',
      render: (_: any, record: any) => (
        <Space size="middle">
          <span>{record.state == 1 ? '未认证' : '已认证'}</span>
        </Space>
      ),
    },
    {
      title: '操作',
      align: 'center',
      key: 'index',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button type="primary" style={{ backgroundColor: '#67c23a' }} onClick={update(record)}>修改</Button>
          <Button type="primary" danger onClick={del(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];
  const update = (record: any) => {
    return () => {
      navigate(`/home/UserInfoAdd`, { state: { record } })
    }
  }
  const onFinish = (values: any) => {
    console.log('Success:', values);
    values.buildingid = values.buildingid
    setUser({
      ...user,
      name: values.name,
      mobile: values.mobile,
      houseno: values.houseno,
      usertype: values.usertype

    })
    getUserInfoList()

  };
  const changePagination = (page: any, psize: any) => {
    setUser({ ...user, page: page, psize: psize })
    console.log(user);
  }
  const [delId, setDelId] = useState<any>()
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setDelId(selectedRowKeys)
    },
  };
  return (
    <div className='userinfo'>
      <div className="useheader">
        <div className='usetitle'>居民管理</div>
      </div>
      <div className="con">
        <Form
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
          className='Form'
        >
          <Form.Item
            label="楼栋"
            name="buildingid"
            className='form'
          >
            <Cascader options={options} onChange={onChange} fieldNames={fiel} placeholder="请选择楼栋" style={{ textAlign: 'left' }} />
          </Form.Item>

          <Form.Item
            label="姓名"
            name="name"
            className='form'
          >
            <Input placeholder='请输入姓名' />
          </Form.Item>
          <Form.Item
            label="电话号"
            name="mobile"
            className='form'
          >
            <Input placeholder='请输入电话号' />
          </Form.Item>
          <Form.Item
            label="房间号"
            name="houseno"
            className='form'
          >
            <Input placeholder='请输入房间号' />
          </Form.Item>
          <Form.Item
            label="用户类型"
            name="usertype"
            className='form'
          >
            <Select allowClear placeholder="请选择">
              {
                typeList.map((item: any) => {
                  return (
                    <Select.Option key={item.id} value={item.id} label={item.name}>
                      {item.name}
                    </Select.Option>
                  )
                })
              }
            </Select>
          </Form.Item>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form>
        <div className="center">
          <Link to={'/home/UserInfoAdd'}><Button style={{ marginRight: "20px" }} type="primary">添加</Button></Link>
          <Button type="primary" style={{ marginRight: "20px" }} danger onClick={selectDel}>批量删除</Button>
          <Button type="primary" style={{ backgroundColor: '#67c23a' }} onClick={updateState}>批量审核</Button>
        </div>

        <div className="table">
          <Table rowSelection={{
            type: 'checkbox',
            ...rowSelection,
          }} rowKey={(record: any) => record.id} bordered pagination={false} columns={columns} dataSource={list} />
        </div>
        <div className="pagination">
          <Pagination
            pageSizeOptions={["5", "10", "15", "20", `${counts}`]}
            defaultCurrent={2}
            total={counts}
            onChange={changePagination}
            showSizeChanger
            showQuickJumper={true}
            showTotal={(counts) => `总共${counts} 条`}
          />
        </div>
      </div>
    </div>
  )
}
export default UserInfo